package com.chanceit.ssss.activity;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.gl.GlobalVariable;
import org.gl.animation.ReverseInterpolator;
import org.gl.customview.Rotate3dAnimation;
import org.gl.customview.charview.LineView;
import org.gl.customview.charview.LineView.DetailPopuWindow;
import org.gl.customview.charview.LineView.onShowDetailInfo;
import org.gl.ui.manger.AjaxCallBackProxy;
import org.gl.utils.Dateutil;
import org.gl.utils.lg;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.chanceit.ssss.data.DataSources;
import com.chanceit.ssss.dialog.DataPickWheelDialog;
import com.chanceit.ssss.dialog.DataPickWheelDialog.DateChangeListener;

public class ReportActivity extends BaseFragmentActivity implements
		OnItemSelectedListener {
	Spinner spinner_data, spinner_type;
	int[][] DataArray = { new int[12], new int[12], new int[12], new int[12] };
	LinearLayout linearLayout;
	private final String[] array_report_type = new String[] { "投诉统计", "客户满意度",
			"预约完成率", "到店用户数", "客户流失数", "客户增长", "消息统计", "客户总数" };
	private final String[] array_report_unit = new String[] { "条", "个", "条",
			"人", "人", "人", "条", "人" };
	private final String[][] array_report_title = new String[][] {
			{ "未完成", "已完成" }, { "★☆☆☆☆ ", "★★☆☆☆", "★★★☆☆", "★★★★☆", "★★★★★" },
			{ "未确定预约", "已确定预约", "已完成预约", "未按时应约" }, { "到店数量" }, { "客户流失数量" },
			{ "客户增长数量" }, { "消息统计" }, { "客户总数" } };
	/**
	 * 对应服务器的接口参数数组
	 */
	private final String[] array_report_type_web = new String[] {
			"complaint_count", "researchResult_count", "reserve_count",
			"maintain_record_count", "company_competition_count",
			"user_growCount", "message_count", "user_totalCount" };
	private final String[] array_report_web_key = new String[] { "Complain",
			"research", "reserve", "maintainRecord", "companyCompetition",
			"userGrow", "message", "userTotal" };
	private final String[] array_timeformat = new String[] { "日", "月", "年" };
	private DataSources ds;
	/**
	 * 当前的时间
	 */
	TextView et_data;
	Rotate3dAnimation mRotate3dAnimation;
	DecelerateInterpolator mDecelerateInterpolator = new DecelerateInterpolator();
	ReverseInterpolator mReverseInterpolator = new ReverseInterpolator();
	LineView lineView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_report);

		isInited = false;
		wave = AnimationUtils.loadAnimation(this, R.anim.wave);
		spinner_data = (Spinner) findViewById(R.id.spinner_data);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				R.layout.spinner_item_check_text, array_timeformat);

		// 设置下拉列表的风格
		adapter.setDropDownViewResource(R.layout.spinner_item_write_text);
		// 将adapter 添加到spinner中
		spinner_data.setAdapter(adapter);
		// 添加事件Spinner事件监听
		spinner_data.setOnItemSelectedListener(this);
		// spinner_data.setSelection(0, true);

		spinner_type = (Spinner) findViewById(R.id.spinner_type);
		ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,
				R.layout.spinner_item_check_text, array_report_type);

		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner_type.setAdapter(adapter2);
		spinner_type.setOnItemSelectedListener(this);
		spinner_type.setSelection(6, true);

		initLineView();
		initDateEditView();
		
	}

	private TextView de_time;
	private TextView de_data;
	private View rl_content;
	private boolean isInited = false;
	private SoundPool sound;
	private int sound_PageFlip;
	private LinearLayout ll_ll_context_tv;
	private Animation wave ;
	class DelaViewHolder {
		TextView count;
		TextView title;
		LinearLayout ll_tv;
	}

	DelaViewHolder[] mDelaViewHolders = new DelaViewHolder[5];

	/**
	 * 初始化统计图模块
	 */
	private void initLineView() {

		de_time = (TextView) findViewById(R.id.tv_current_time);
		de_data = (TextView) findViewById(R.id.time);
		rl_content = findViewById(R.id.ll_context);
		ll_ll_context_tv = (LinearLayout) findViewById(R.id.ll_ll_context_tv);
		sound = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
		sound_PageFlip = sound.load(this, R.raw.page_flip_short, 1);
		linearLayout = (LinearLayout) findViewById(R.id.body);
		lineView = new LineView(this);
		lineView.setSoundEffectsEnabled(true);
		for (int i = 0; i < mDelaViewHolders.length; i++) {
			mDelaViewHolders[i] = new DelaViewHolder();
		}
		mDelaViewHolders[0].count = (TextView) findViewById(R.id.tv_x_1);
		mDelaViewHolders[0].title = (TextView) findViewById(R.id.tv_u_1);
		mDelaViewHolders[0].ll_tv = (LinearLayout) findViewById(R.id.ll_tv_1);

		mDelaViewHolders[1].count = (TextView) findViewById(R.id.tv_x_2);
		mDelaViewHolders[1].title = (TextView) findViewById(R.id.tv_u_2);
		mDelaViewHolders[1].ll_tv = (LinearLayout) findViewById(R.id.ll_tv_2);

		mDelaViewHolders[2].count = (TextView) findViewById(R.id.tv_x_3);
		mDelaViewHolders[2].title = (TextView) findViewById(R.id.tv_u_3);
		mDelaViewHolders[2].ll_tv = (LinearLayout) findViewById(R.id.ll_tv_3);

		mDelaViewHolders[3].count = (TextView) findViewById(R.id.tv_x_4);
		mDelaViewHolders[3].title = (TextView) findViewById(R.id.tv_u_4);
		mDelaViewHolders[3].ll_tv = (LinearLayout) findViewById(R.id.ll_tv_4);

		mDelaViewHolders[4].count = (TextView) findViewById(R.id.tv_x_5);
		mDelaViewHolders[4].title = (TextView) findViewById(R.id.tv_u_5);
		mDelaViewHolders[4].ll_tv = (LinearLayout) findViewById(R.id.ll_tv_5);

		monShowDetailInfo = new onShowDetailInfo() {
			

			@Override
			public void showDetailInfo(DetailPopuWindow... mDetailPopuWindow) {
				try {
					String unit = array_report_unit[spinner_type
							.getSelectedItemPosition()];
					int length = mDetailPopuWindow.length > mDelaViewHolders.length ? mDelaViewHolders.length
							: mDetailPopuWindow.length;
					ll_ll_context_tv.setWeightSum(length);
					String[] titles = array_report_title[spinner_type
							.getSelectedItemPosition()];
					for (int i = 0; i < mDetailPopuWindow.length; i++) {
						DetailPopuWindow detailPopuWindow = mDetailPopuWindow[i];
						mDelaViewHolders[i].title.setText(titles[i]);
						mDelaViewHolders[i].count
								.setText(detailPopuWindow.content + unit);
						mDelaViewHolders[i].ll_tv.setVisibility(View.VISIBLE);
					}
					for (int i = mDelaViewHolders.length - 1; i > length - 1; i--) {
						mDelaViewHolders[i].ll_tv.setVisibility(View.GONE);
					}
					if (spinner_data.getSelectedItemPosition() != 2) {
						de_time.setText(de_data.getText()
								+ "-"
								+ String.format("%02d",
										(mDetailPopuWindow[0].index + 1)));
					} else {
						de_time.setText(de_data.getText());
					}
					de_time.startAnimation(wave );
				} catch (Exception e) {
					e.printStackTrace();
					lg.e(TAG, "sync array out of range");
				}

			}
		};
		linearLayout.addView(lineView);
		mRotate3dAnimation = new Rotate3dAnimation(0, 360,
				GlobalVariable.disPlay_w / 2, GlobalVariable.disPlay_w / 2,
				40.0f, false);
		mRotate3dAnimation.setDuration(1000);
		mRotate3dAnimation.setFillAfter(true);
		mRotate3dAnimation.setInterpolator(mDecelerateInterpolator);
		// rl_content.startAnimation(mRotate3dAnimation);
	}

	/**
	 * 获取网络上的统计数据
	 * 
	 * @param time
	 */
	protected void changeData(String time) { // TODO
		// int nextdateInterval = 0;
		// nextdateInterval = getNextDateInterval();
		//
		// String tempSting = Dateutil.getNextDayString(et_data.getText()
		// .toString(), 0);
		lg.i(TAG, "changeData->time:" + time);
		getData(new AjaxCallBackProxy<String>(findViewById(R.id.loading)) {
			@Override
			public void onStart() {
				super.onStart();
				spinner_type.setEnabled(false);
				spinner_data.setEnabled(false);
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				super.onFailure(t, errorNo, strMsg);
				spinner_type.setEnabled(true);
				spinner_data.setEnabled(true);
			}

			@Override
			public void onSuccess(String t) {
				super.onSuccess(t);
				spinner_type.setEnabled(true);
				spinner_data.setEnabled(true);
				if (TextUtils.isEmpty(t)) {
					onFailure(null, 0, "null data");
					return;
				}
				lg.i(TAG, t);
				JSONObject ja;
				try {
					ja = new JSONObject(t);
					JSONArray result = ja
							.optJSONArray(array_report_web_key[spinner_type
									.getSelectedItemPosition()]);
					int temp[][] = new int[result.length()][];
					for (int i = 0; i < result.length(); i++) {
						JSONArray data = result.getJSONObject(i).getJSONArray( // 多个线条
								"statistics");
						if (spinner_data.getSelectedItemPosition() != 2) {

							temp[i] = new int[data.length()];
							for (int j = 0; j < data.length(); j++) {
								temp[i][j] = data.optInt(j);
							}
						} else {
							temp[i] = new int[data.length()];
							for (int j = 0; j < data.length(); j++) {
								temp[i][j] = data.optJSONObject(j).optInt(
										"count");
							}
						}
					}
					DataArray = temp;
					notiLineViewDataChange();
				} catch (JSONException e) {
					e.printStackTrace();
					onFailure(null, 0, "" + t);
				} catch (Exception e) {
					e.printStackTrace();
					onFailure(null, 0, "" + t);
				} finally {
					isInited = true;
				}

			}
		});

	}

	LineView.onShowDetailInfo monShowDetailInfo;

	protected void notiLineViewDataChange() {
		lg.i(TAG, "notiLineViewDataChange:" + linearLayout.getMeasuredHeight());
		lineView.initValue(GlobalVariable.disPlay_w,
				linearLayout.getMeasuredHeight(), DataArray);
		lineView.startAnimation(mRotate3dAnimation);
		lineView.setOnShowDetailInfo(monShowDetailInfo);
		sound.play(sound_PageFlip, 1, 1, 0, 0, 1);
	}

	private int getNextDateInterval() {
		int nextdateInterval = 0;
		switch (spinner_data.getSelectedItemPosition()) {
		case 0:// for day
			nextdateInterval = 30;
			break;
		case 1:// for month
			nextdateInterval = 365;
			break;
		case 2:// for yeah
		default:
			break;
		}
		return nextdateInterval;
	}

	public final static SimpleDateFormat YYYYMM = new SimpleDateFormat(
			"yyyy-MM");
	public final static SimpleDateFormat YYYY = new SimpleDateFormat("yyyy");

	private void initDateEditView() {
		et_data = (TextView) findViewById(R.id.time);
		String currentTimeString = Dateutil.getTimeString(YYYYMM,
				System.currentTimeMillis());
		final com.chanceit.ssss.dialog.DataPickWheelDialog mMonthPickWheelDialog = new DataPickWheelDialog(
				this, DataPickWheelDialog.StyleMonthPick);

		final com.chanceit.ssss.dialog.DataPickWheelDialog mYearPickWheelDialog = new DataPickWheelDialog(
				this, DataPickWheelDialog.StyleYearPick);
		mMonthPickWheelDialog.setCurrentDate(
				Integer.parseInt(currentTimeString.split("-")[0]),
				Integer.parseInt(currentTimeString.split("-")[1]));
		mYearPickWheelDialog.setCurrentDate(
				Integer.parseInt(currentTimeString.split("-")[0]),
				Integer.parseInt(currentTimeString.split("-")[1]));
		DateChangeListener mDateChangeListener = new DateChangeListener() {
			@Override
			public void dateChange(String previousTime, String currentTime) {
				changeTimeForamat(currentTime);
				changeData(currentTime);
			}
		};

		mMonthPickWheelDialog.setDateChangeListener(mDateChangeListener);
		mYearPickWheelDialog.setDateChangeListener(mDateChangeListener);
		et_data.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				switch (spinner_data.getSelectedItemPosition()) {
				case 0:
					mMonthPickWheelDialog.show();
					break;
				case 1:
					mYearPickWheelDialog.show();
					break;

				default:
					break;
				}

			}
		});
		et_data.setText(currentTimeString);
		ds = new DataSources();

		initData(currentTimeString);
	}

	private void initData(String currentTimeString) {
		changeData(currentTimeString);
	}

	private void getData(AjaxCallBackProxy<String> aj) {
		Calendar calender = Calendar.getInstance();

		String web_type = array_report_type_web[spinner_type
				.getSelectedItemPosition()];
		switch (spinner_data.getSelectedItemPosition()) {
		case 0:// for day
			calender.setTimeInMillis(Dateutil.convert2long(et_data.getText()
					.toString(), "yyyy-MM"));
			ds.getReportByDay(null, web_type, "" + calender.get(Calendar.YEAR),
					calender.get(Calendar.MONTH) + 1 + "", aj);
			break;
		case 1:// for month
			calender.setTimeInMillis(Dateutil.convert2long(et_data.getText()
					.toString(), "yyyy"));
			ds.getReportByMonth(null, web_type,
					"" + calender.get(Calendar.YEAR), aj);
			break;
		case 2:// for yeah
			ds.getReportByYear(null, web_type, aj);
			break;

		default:
			break;
		}

	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		if (isInited) {
			// if (R.id.spinner_data == arg0.getId()) {
			String currentTimeString = Dateutil.getTimeString(YYYYMM,
					System.currentTimeMillis());
			changeTimeForamat(currentTimeString);
			changeData(currentTimeString);
			// }
		}

	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	}

	private void changeTimeForamat(String currentTime) {

		switch (spinner_data.getSelectedItemPosition()) {
		case 0:
			et_data.setText(currentTime);
			break;
		case 1:
			et_data.setText(currentTime.split("-")[0]);
			break;
		case 3:
			et_data.setText(currentTime.split("-")[0]);
			break;
		default:
			break;
		}
	}
}
